local fk__qianlin = fk.CreateSkill {

  name = "fk__qianlin",

  tags = { Skill.Compulsory, },

}

local U = require "packages/utility/utility"


fk__qianlin:addEffect(fk.BeforeCardsMove, {
  name = "fk__qianlin",
  events = {fk.BeforeCardsMove},
  frequency = Skill.Compulsory,
  anim_type = "defensive",
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(fk__qianlin.name) or player:isAllNude() or player == player.room.current then return end
    local ids = {}
    for _, move in ipairs(data) do
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if (info.fromArea >= 1 and info.fromArea <= 3) then
            table.insert(ids, info.cardId)
          end
        end
      end
    end
    if #ids == 0 then return end
    local e = player.room.logic:getCurrentEvent().parent
    if e and (e.event == GameEvent.UseCard or e.event == GameEvent.RespondCard) then
      if e.data[1].from == player.id then
        for _, id in ipairs(Card:getIdList(e.data[1].card)) do
          table.removeOne(ids, id)
        end
      end
    end
    if #ids > 0 then
      event:setCostData(self, ids)
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local ids = event:getCostData(self)
    local sub_types = {}
    for _, id in ipairs(ids) do
      if player.room:getCardArea(id) == Card.PlayerEquip then
        table.insert(sub_types, Fk:getCardById(id).sub_type)
      end
    end
    local throw_moves = {}
    for _, move in ipairs(data) do
      local move_info = table.simpleClone(move.moveInfo)
      if move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if table.contains(ids, info.cardId) then
            table.removeOne(move_info, info)
          end
        end
      end
      local throw_info = {}
      if move.to == player.id and move.toArea == Card.PlayerEquip then -- 处理置换装备的情况
        for i = #move_info, 1, -1 do
          local info = move_info[i]
          if table.contains(sub_types, Fk:getCardById(info.cardId).sub_type) then
            table.insert(throw_info, table.remove(move_info, i))
          end
        end
      end
      move.moveInfo = move_info
      if #throw_info > 0 then
        local _move = table.simpleClone(move)
        _move.moveInfo = throw_info
        _move.moveReason = fk.ReasonPutIntoDiscardPile
        _move.to = nil
        _move.toArea = Card.DiscardPile
        table.insert(throw_moves, _move)
      end
    end
    if #throw_moves > 0 then
      table.insertTable(data, throw_moves)
    end
  end,
})

return fk__qianlin